﻿using CCWin;
using ERPWinFormWork.Product;
using ERPWinFormWork.Sales.DTO;
using ERPWinFormWork.Sales.ErrorCode;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERPWinFormWork.Sales
{
    public partial class Form1 : CCSkinMain

    {

        private ApiClient _apiClient;

        private int PageIndex { get; set; } = 1;
        private int PageSize { get; set; } = 15;
        private int TotalPages { get; set; } = 1;
        private int TotalSize { get; set; }
        public Form1()
        {

            InitializeComponent();
            // 初始化 API 客户端（替换为你的实际 API 基础地址）
            _apiClient = new ApiClient(AppConfig.ApiBaseUrl);
            dgvGetDiscount.CellContentClick += dgvGetDiscount_CellContentClick;

            GetCustomerSelect();
            GetDataQuotation();

           


        }



        /// <summary>
        /// 菜单 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void skinTabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (skinTabControl1.SelectedTab == txtQuotationPage)
            {
                // 检查是否已经加载过数据，避免重复加载
                if (dgvQuotation.DataSource == null)
                {
                    GetCustomerSelect();
                    GetDataQuotation();

                }
            }

            if (skinTabControl1.SelectedTab == lblDiscountTime)
            {
                // 检查是否已经加载过数据，避免重复加载
                if (dgvGetDiscount.DataSource == null)
                {
                    GetData();

                }
            }
            if (skinTabControl1.SelectedTab == CustomerPrice)
            {
                // 检查是否已经加载过数据，避免重复加载
                if (dgvCustomerPriceGet.DataSource == null)
                {
                    GetDataCustomerPrice();

                }
            }

            if (skinTabControl1.SelectedTab == Contract)
            {
                // 检查是否已经加载过数据，避免重复加载
                if (dgvContractGet.DataSource == null)
                {
                    GetContractSelect();
                    GetContractData();
                  
                }
            }
            if(skinTabControl1.SelectedTab == SalesTicket)
            {
                // 检查是否已经加载过数据，避免重复加载
                if (dgvTicketGet.DataSource == null)
                {
                    GetTicketSelect();
                    GeTicketData();


                }
            }




        }

        #region 折扣方案
        private void btnAdd_Click(object sender, EventArgs e)
        {
            DiscountAddForm discountAddForm = new DiscountAddForm(this);
            discountAddForm.Show();
            
        }


        public async void GetData()
        {
            var parameters = new Dictionary<string, string>
                {
                    { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },
                    { "Name", this.txtDiscountName.Text.Trim() },
                    { "Createtime", this.dtpCreateTime.Text },
                };


            var response = await _apiClient.GetAsync<ApiResponse<List<Discount_SchemeDTO>>>(
                    endpoint: "Sales/DiscountGet",
                    parameters: parameters
                );
            if (response != null && response.code == 200)
            {
                dgvGetDiscount.DataSource = response.pageData;
                TotalPages = response.totalCount;
                TotalSize = Convert.ToInt32(Math.Ceiling(TotalPages * 1.0 / PageSize));
                this.lblcount.Text = TotalSize.ToString();

                
                dgvGetDiscount.Columns["Id"].Visible = false;
                dgvGetDiscount.Columns["Product_Id"].Visible = false;
                
                AddOperationColumns();
            }
        }

        private void AddOperationColumns()
        {
            string[] columnNames = { "Details", "Edit", "Delete" };
            string[] headerTexts = { "详情", "编辑", "删除" };

            for (int i = 0; i < columnNames.Length; i++)
            {
                if (dgvGetDiscount.Columns[columnNames[i]] == null)
                {
                    var col = new DataGridViewButtonColumn();
                    col.Name = columnNames[i];
                    col.HeaderText = headerTexts[i];
                    col.Text = headerTexts[i];
                    col.UseColumnTextForButtonValue = true;
                    dgvGetDiscount.Columns.Add(col);
                }
            }
        }

        private async void dgvGetDiscount_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                Discount_SchemeDTO item = dgvGetDiscount.Rows[e.RowIndex].DataBoundItem as Discount_SchemeDTO;
                if (item != null)
                {
                    string colName = dgvGetDiscount.Columns[e.ColumnIndex].Name;
                    if (colName == "Details")
                    {
                        new DiscountDetailsForm(item.Id).ShowDialog();
                    }
                    else if (colName == "Edit")
                    {
                        //new DiscountAddForm(this, DiscountAddForm.Mode.Edit, item.Id).ShowDialog();
                        //GetData();
                    }
                    else if (colName == "Delete")
                    {
                        if (MessageBox.Show("确认删除此折扣方案?", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            var data = new { id = item.Id };
                            var response = await _apiClient.PostAsync<object, ApiResponse<string>>("Sales/DiscountDel", data);
                            if (response != null && response.code == 200)
                            {
                                MessageBox.Show("删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                GetData();
                            }
                            else
                            {
                                MessageBox.Show($"删除失败: {response?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                }
            }
        }


       



        
        private void btnPrevPage_Click(object sender, EventArgs e)
        {
            if (PageIndex > 1)
            {
                PageIndex--;
                txtCurrentPage.Text = PageIndex.ToString();
                GetData();
            }
        }

        private void btnNextPage_Click(object sender, EventArgs e)
        {
            if (PageIndex< TotalSize)
            {
                PageIndex++;
                txtCurrentPage.Text = PageIndex.ToString();
                GetData();
            }
        }

        private void btnGetWhere_Click(object sender, EventArgs e)
        {
            GetData();
        }

        private void btnreset_Click(object sender, EventArgs e)
        {
            this.txtDiscountName.Text = "";
            this.dtpCreateTime.Text = "";
        }

        private async void btnDao_Click_1(object sender, EventArgs e)
        {
            var parameters = new Dictionary<string, string>
            {
                { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },
                    { "Name", this.txtDiscountName.Text.Trim() },
                    { "Createtime", this.dtpCreateTime.Text },
            };

            // Assuming export endpoint is Sales/DiscountExport and returns ApiResponse<string> with file path or message
            byte[] excelBytes = await _apiClient.GetBytesAsync(
            endpoint: "Sales/DiscountGetExport", // 后端导出接口名（与 [HttpGet("DiscountGetExport")] 匹配）
            parameters: parameters
             );

            using (var saveDialog = new SaveFileDialog())
            {
                saveDialog.Filter = "Excel文件 (*.xlsx)|*.xlsx|所有文件 (*.*)|*.*"; // 只允许保存xlsx格式
                saveDialog.Title = "保存折扣方案导出文件";
                // 默认文件名：与后端一致（带时间戳，避免重复）
                saveDialog.FileName = $"折扣方案_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                saveDialog.RestoreDirectory = true; // 打开时默认显示上次保存的路径

                // 若用户选择了保存路径
                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        // 将二进制流写入本地文件（完成保存）
                        System.IO.File.WriteAllBytes(saveDialog.FileName, excelBytes);

                        // 导出成功提示 + 可选打开文件
                        DialogResult openChoice = MessageBox.Show(
                            $"导出成功！\n文件已保存到：\n{saveDialog.FileName}\n是否立即打开文件？",
                            "导出成功",
                            MessageBoxButtons.YesNo,
                            MessageBoxIcon.Information
                        );

                        if (openChoice == DialogResult.Yes)
                        {
                            // 用系统默认程序（如WPS/Office）打开Excel
                            System.Diagnostics.Process.Start(saveDialog.FileName);
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        // 处理“无保存权限”错误（如选择C盘根目录）
                        MessageBox.Show("导出失败：没有文件保存权限！请选择桌面或其他有权限的路径。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    catch (System.IO.IOException ex)
                    {
                        // 处理“文件被占用”错误（如Excel已打开）
                        MessageBox.Show($"导出失败：文件被占用！\n原因：{ex.Message}\n请先关闭已打开的同名Excel文件。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }





        }

        #endregion


        #region 销售报价

       

        /// <summary>
        /// 显示销售
        /// </summary>
        public async void GetDataQuotation()
        {
            var parameters = new Dictionary<string, string>
                {
                    { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },
                    { "Id", cbocustomer.SelectedValue == null ? string.Empty : cbocustomer.SelectedValue.ToString() },
                    { "Name", this.txtQuotationNumber.Text.Trim() },
                    { "CreateTime", this.dtpQuotationCreate.Text },
                };


            var response = await _apiClient.GetAsync<ApiResponse<List<QuotationGetDTO>>>(
                    endpoint: "Sales/QuotationGet",
                    parameters: parameters
                );
            if (response != null && response.code == 200)
            {
                dgvQuotation.DataSource = response.pageData;
                TotalPages = response.totalCount;
                TotalSize = Convert.ToInt32(Math.Ceiling(TotalPages * 1.0 / PageSize));
                this.lblQuotationSize.Text = TotalSize.ToString();

                dgvQuotation.Columns["Id"].Visible = false;
                dgvQuotation.Columns["Customer_Id"].Visible = false;
                AddQuotationColumns();
            }
        }

        /// <summary>
        /// 查询按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuotationGet_Click_1(object sender, EventArgs e)
        {
            GetDataQuotation();
        }

        /// <summary>
        /// 重置按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnresetQuotation_Click(object sender, EventArgs e)
        {
            txtQuotationNumber.Text = "";
            cbocustomer.SelectedIndex = 0;
            dtpQuotationCreate.text = "";
        }
        /// <summary>
        /// 添加 操作列
        /// </summary>
        private void AddQuotationColumns()
        {
            string[] columnNames = { "Details", "Edit", "Delete" };
            string[] headerTexts = { "详情", "编辑", "删除" };

            for (int i = 0; i < columnNames.Length; i++)
            {
                if (dgvQuotation.Columns[columnNames[i]] == null)
                {
                    var col = new DataGridViewButtonColumn();
                    col.Name = columnNames[i];
                    col.HeaderText = headerTexts[i];
                    col.Text = headerTexts[i];
                    col.UseColumnTextForButtonValue = true;
                    dgvQuotation.Columns.Add(col);
                }
            }
        }


        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuotationlast_Click(object sender, EventArgs e)
        {
            if (PageIndex > 1)
            {
                PageIndex--;
                Pageindex.Text = PageIndex.ToString();
                GetDataQuotation();
            }
        }
        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuotationNext_Click(object sender, EventArgs e)
        {
            if (PageIndex < TotalSize)
            {
                PageIndex++;
                Pageindex.Text = PageIndex.ToString();
                GetDataQuotation();
            }
        }



        /// <summary>
        /// 查询按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuotationGet_Click(object sender, EventArgs e)
        {
            GetDataQuotation();
        }


        /// <summary>
        /// 报价折扣导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void skinButton3_Click(object sender, EventArgs e)
        {
            var parameters = new Dictionary<string, string>
            {
                    { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },
                    { "Name", this.txtDiscountName.Text.Trim() },
                    { "Createtime", this.dtpCreateTime.Text },
            };

            // Assuming export endpoint is Sales/DiscountExport and returns ApiResponse<string> with file path or message
            byte[] excelBytes = await _apiClient.GetBytesAsync(
            endpoint: "Sales/QuotationGetExport",
            parameters: parameters
             );

            using (var saveDialog = new SaveFileDialog())
            {
                saveDialog.Filter = "Excel文件 (*.xlsx)|*.xlsx|所有文件 (*.*)|*.*"; // 只允许保存xlsx格式
                saveDialog.Title = "保存折扣方案导出文件";
                // 默认文件名：与后端一致（带时间戳，避免重复）
                saveDialog.FileName = $"销售报价_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                saveDialog.RestoreDirectory = true; // 打开时默认显示上次保存的路径

                // 若用户选择了保存路径
                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        // 将二进制流写入本地文件（完成保存）
                        System.IO.File.WriteAllBytes(saveDialog.FileName, excelBytes);

                        // 导出成功提示 + 可选打开文件
                        DialogResult openChoice = MessageBox.Show(
                            $"导出成功！\n文件已保存到：\n{saveDialog.FileName}\n是否立即打开文件？",
                            "导出成功",
                            MessageBoxButtons.YesNo,
                            MessageBoxIcon.Information
                        );

                        if (openChoice == DialogResult.Yes)
                        {
                            // 用系统默认程序（如WPS/Office）打开Excel
                            System.Diagnostics.Process.Start(saveDialog.FileName);
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        // 处理“无保存权限”错误（如选择C盘根目录）
                        MessageBox.Show("导出失败：没有文件保存权限！请选择桌面或其他有权限的路径。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    catch (System.IO.IOException ex)
                    {
                        // 处理“文件被占用”错误（如Excel已打开）
                        MessageBox.Show($"导出失败：文件被占用！\n原因：{ex.Message}\n请先关闭已打开的同名Excel文件。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
        /// <summary>
        /// 显示客户
        /// </summary>
        private async void GetCustomerSelect()
        {
            var response = await _apiClient.GetAsync<ApiResponse<List<Customer>>>(
                    endpoint: "Sales/CustomerGet"
                );
            if (response != null && response.code == 200)
            {
                var customerList = new List<Customer>
                {
                new Customer { id = 0, Customer_Name = "请选择"
                }
            };
                customerList.AddRange(response.data);
                cbocustomer.DataSource = customerList;
                cbocustomer.DisplayMember = "Customer_Name";//指定显示的字段
                cbocustomer.ValueMember = "id";
                cbocustomer.SelectedIndex = 0;
            }
        }

        private void btnQuotationAdd_Click(object sender, EventArgs e)
        {
            QuotationAddForm quotationAddForm = new QuotationAddForm();
            quotationAddForm.Show();
        }

        private void btnQuotationAdd1_Click(object sender, EventArgs e)
        {
            QuotationAddForm quotationAddForm = new QuotationAddForm();
            quotationAddForm.Show();
        }

        private void dgvQuotation_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                QuotationGetDTO item = dgvQuotation.Rows[e.RowIndex].DataBoundItem as QuotationGetDTO;
                if (item != null)
                {
                    string colName = dgvQuotation.Columns[e.ColumnIndex].Name;
                    if (colName == "Details")
                    {

                        using (QuotationDetailsForm productForm = new QuotationDetailsForm(item.Id))
                        {

                            if (productForm.ShowDialog() == DialogResult.OK)
                            {

                            }
                        }

                    }
                    else if (colName == "Edit")
                    {
                        //new DiscountAddForm(this, DiscountAddForm.Mode.Edit, item.Id).ShowDialog();
                        //GetData();
                    }
                    else if (colName == "Delete")
                    {
                        //if (MessageBox.Show("确认删除此折扣方案?", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        //{
                        //    var data = new { id = item.Id };
                        //    var response = await _apiClient.PostAsync<object, ApiResponse<string>>("Sales/DiscountDel", data);
                        //    if (response != null && response.code == 200)
                        //    {
                        //        MessageBox.Show("删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        //        GetData();
                        //    }
                        //    else
                        //    {
                        //        MessageBox.Show($"删除失败: {response?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        //    }
                        //}
                    }
                }
            }
        }


        #endregion


        #region 客户单价

        public async void GetDataCustomerPrice()
        {
            var parameters = new Dictionary<string, string>
                {
                    { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },
                    { "Name", this.txtCustomerName.Text.Trim() },
                    { "Createtime", this.dtpCustomerPriceTime.Text },
                };


            var response = await _apiClient.GetAsync<ApiResponse<List<CustomerPriceGetDTO>>>(
                    endpoint: "Sales/CustomerPriceGet",
                    parameters: parameters
                );
            if (response != null && response.code == 200)
            {
                dgvCustomerPriceGet.DataSource = response.pageData;
                TotalPages = response.totalCount;
                TotalSize = Convert.ToInt32(Math.Ceiling(TotalPages * 1.0 / PageSize));
                this.lblCustomerPriceCount.Text = TotalSize.ToString();
                dgvCustomerPriceGet.Columns["Id"].Visible = false;
                dgvCustomerPriceGet.Columns["Customer_Id"].Visible = false;
                AddCustomerPriceColumns();
            }
        }

        /// <summary>
        /// 添加 操作列
        /// </summary>
        private void AddCustomerPriceColumns()
        {
            string[] columnNames = { "Details", "Edit", "Delete" };
            string[] headerTexts = { "详情", "编辑", "删除" };

            for (int i = 0; i < columnNames.Length; i++)
            {
                if (dgvQuotation.Columns[columnNames[i]] == null)
                {
                    var col = new DataGridViewButtonColumn();
                    col.Name = columnNames[i];
                    col.HeaderText = headerTexts[i];
                    col.Text = headerTexts[i];
                    col.UseColumnTextForButtonValue = true;
                    dgvQuotation.Columns.Add(col);
                }
            }
        }

        /// <summary>
        /// 查询按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void skinButton2_Click(object sender, EventArgs e)
        {
            GetDataCustomerPrice();
        }

        /// <summary>
        /// 重置按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void skinButton1_Click(object sender, EventArgs e)
        {
            txtCustomerName.Text = "";
            dtpCustomerPriceTime.Text = "";
        }

        private async void btnCustomerPriceDao_Click(object sender, EventArgs e)
        {
            var parameters = new Dictionary<string, string>
            {
                   { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },
                    { "Name", this.txtCustomerName.Text.Trim() },
                    { "Createtime", this.dtpCustomerPriceTime.Text },
            };

            // Assuming export endpoint is Sales/DiscountExport and returns ApiResponse<string> with file path or message
            byte[] excelBytes = await _apiClient.GetBytesAsync(
            endpoint: "Sales/CustomerPriceGetExport",
            parameters: parameters
             );

            using (var saveDialog = new SaveFileDialog())
            {
                saveDialog.Filter = "Excel文件 (*.xlsx)|*.xlsx|所有文件 (*.*)|*.*"; // 只允许保存xlsx格式
                saveDialog.Title = "保存客户单价导出文件";
                // 默认文件名：与后端一致（带时间戳，避免重复）
                saveDialog.FileName = $"客户单价_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                saveDialog.RestoreDirectory = true; // 打开时默认显示上次保存的路径

                // 若用户选择了保存路径
                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        // 将二进制流写入本地文件（完成保存）
                        System.IO.File.WriteAllBytes(saveDialog.FileName, excelBytes);

                        // 导出成功提示 + 可选打开文件
                        DialogResult openChoice = MessageBox.Show(
                            $"导出成功！\n文件已保存到：\n{saveDialog.FileName}\n是否立即打开文件？",
                            "导出成功",
                            MessageBoxButtons.YesNo,
                            MessageBoxIcon.Information
                        );

                        if (openChoice == DialogResult.Yes)
                        {
                            // 用系统默认程序（如WPS/Office）打开Excel
                            System.Diagnostics.Process.Start(saveDialog.FileName);
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        // 处理“无保存权限”错误（如选择C盘根目录）
                        MessageBox.Show("导出失败：没有文件保存权限！请选择桌面或其他有权限的路径。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    catch (System.IO.IOException ex)
                    {
                        // 处理“文件被占用”错误（如Excel已打开）
                        MessageBox.Show($"导出失败：文件被占用！\n原因：{ex.Message}\n请先关闭已打开的同名Excel文件。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        private void btnCustomerPriceAdd_Click(object sender, EventArgs e)
        {
            CustomerPriceAddForm customerPriceAddForm = new CustomerPriceAddForm(this);
            customerPriceAddForm.Show();
        }

        #endregion

        #region 销售合同

        /// <summary>
        /// 显示销售
        /// </summary>
        public async void GetContractData()
        {
            var parameters = new Dictionary<string, string>
                {
                    { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },
                    { "Id", cboContractCustomer.SelectedValue == null ? string.Empty : cboContractCustomer.SelectedValue.ToString() },
                    { "Name", this.txtContractName.Text.Trim() },
                    { "CreateTime", this.dtpContractTime.Text },
                };


            var response = await _apiClient.GetAsync<ApiResponse<List<Sales_ContractDTO>>>(
                    endpoint: "Sales/ContractGet",
                    parameters: parameters
                );
            if (response != null && response.code == 200)
            {
                dgvContractGet.DataSource = response.pageData;
                TotalPages = response.totalCount;
                TotalSize = Convert.ToInt32(Math.Ceiling(TotalPages * 1.0 / PageSize));
                this.lblcontractSize.Text = TotalSize.ToString();
                dgvContractGet.Columns["Id"].Visible = false;
                dgvContractGet.Columns["Customer_Id"].Visible = false;
                AddContractColumns();
            }
        }

        private void AddContractColumns()
        {
            string[] columnNames = { "Add", "Details", "Edit", "Delete", "Audit" };
            string[] headerTexts = { "生成销售单", "详情", "编辑", "删除", "审核" };

            for (int i = 0; i < columnNames.Length; i++)
            {
                if (dgvContractGet.Columns[columnNames[i]] == null)
                {
                    var col = new DataGridViewButtonColumn();
                    col.Name = columnNames[i];
                    col.HeaderText = headerTexts[i];
                    col.Text = headerTexts[i];
                    col.UseColumnTextForButtonValue = true;
                    dgvContractGet.Columns.Add(col);
                }
            }
        }



        private async void dgvContractGet_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                Sales_ContractDTO item = dgvContractGet.Rows[e.RowIndex].DataBoundItem as Sales_ContractDTO;
                if (item != null)
                {
                    string colName = dgvContractGet.Columns[e.ColumnIndex].Name;

                    // 审核按钮处理
                    if (colName == "Audit")
                    {
                        // 如果合同已经审核，提示用户
                        if (item.Audit_State != "待审核")
                        {
                            MessageBox.Show("此合同已经审核通过，无需再次审核！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }

                        // 创建审核对话框
                        using (var auditDialog = new Form())
                        {
                            auditDialog.Text = "合同审核";
                            auditDialog.Width = 300;
                            auditDialog.Height = 200;
                            auditDialog.StartPosition = FormStartPosition.CenterParent;

                            // 添加单选按钮
                            var rbPass = new RadioButton();
                            rbPass.Text = "审核通过";
                            rbPass.Location = new Point(50, 50);
                            rbPass.Checked = true;

                            var rbFail = new RadioButton();
                            rbFail.Text = "审核失败";
                            rbFail.Location = new Point(50, 80);

                            // 添加确定和取消按钮
                            var btnOK = new Button();
                            btnOK.Text = "确定";
                            btnOK.Location = new Point(60, 120);
                            btnOK.DialogResult = DialogResult.OK;

                            var btnCancel = new Button();
                            btnCancel.Text = "取消";
                            btnCancel.Location = new Point(150, 120);
                            btnCancel.DialogResult = DialogResult.Cancel;

                            // 添加到对话框
                            auditDialog.Controls.Add(rbPass);
                            auditDialog.Controls.Add(rbFail);
                            auditDialog.Controls.Add(btnOK);
                            auditDialog.Controls.Add(btnCancel);

                            // 设置按钮为默认接受和取消
                            auditDialog.AcceptButton = btnOK;
                            auditDialog.CancelButton = btnCancel;

                            // 显示对话框
                            if (auditDialog.ShowDialog() == DialogResult.OK)
                            {
                                // 准备审核数据
                                // var auditData = new
                                // {
                                //     id = item.Id,
                                //     auditMessage = rbPass.Checked ? "通过" : "失败",
                                // };

                                // 调用审核API
                               var response = await _apiClient.PostAsync<object, ApiResponse<string>>(
                                 endpoint: "Sales/ContractAudit",
                                 data: new { id = item.Id, auditMessage = rbPass.Checked ? "审核通过" : "审核失败" }
                                 );
                                if (response != null && response.code == 200)
                                {
                                    MessageBox.Show("审核成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    // 刷新数据
                                    GetContractData();
                                }
                                else
                                {
                                    MessageBox.Show($"审核失败: {response?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            }
                        }
                    }
                    // 已有的其他按钮处理逻辑...
                    else if(colName == "Add")
                    {
                        if(item.Audit_State!="审核通过")
                        {
                            MessageBox.Show("审核未通过不能生成销售单", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                        if (MessageBox.Show("确认添加销售单?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {

                            TicketAddCommand ticketAddCommand = new TicketAddCommand();
                            
                            ticketAddCommand.ticketCommandDTO = new TicketCommandDTO()
                            {
                                Address=item.Address,
                                Contract_Number = item.Contract_Number,
                                Customer_Id = item.Customer_Id,
                                Delivery_Time=item.Signed_Time,
                                Price=item.Contrac_Money,
                                Price_Tex = item.Contrac_Money,
                                Sales_Time=item.CreateTime,
                                Tax_Rate=(decimal)0.03
                            };

                            var response = await _apiClient.PostAsync<TicketAddCommand, ApiResponse<string>>("Sales/TicketAdd", ticketAddCommand);
                            if (response != null && response.code == 200)
                            {
                                MessageBox.Show("添加成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                GetContractData();
                            }
                            else
                            {
                                MessageBox.Show($"添加失败: {response?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                    else if (colName == "Details")
                    {

                    }
                    else if (colName == "Edit")
                    {
                      
                    }
                    else if (colName == "Delete")
                    {
                        //if (MessageBox.Show("确认删除此折扣方案?", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        //{
                        //    var data = new { id = item.Id };
                        //    var response = await _apiClient.PostAsync<object, ApiResponse<string>>("Sales/DiscountDel", data);
                        //    if (response != null && response.code == 200)
                        //    {
                        //        MessageBox.Show("删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        //        GetData();
                        //    }
                        //    else
                        //    {
                        //        MessageBox.Show($"删除失败: {response?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        //    }
                        //}
                    }
                }
            }
        }

        /// <summary>
        /// 显示客户
        /// </summary>
        private async void GetContractSelect()
        {
            var response = await _apiClient.GetAsync<ApiResponse<List<Customer>>>(
                    endpoint: "Sales/CustomerGet"
                );
            if (response != null && response.code == 200)
            {
                var customerList = new List<Customer>
                {
                new Customer { id = 0, Customer_Name = "请选择"
                }
            };
                customerList.AddRange(response.data);
                cboContractCustomer.DataSource = customerList;
                cboContractCustomer.DisplayMember = "Customer_Name";//指定显示的字段
                cboContractCustomer.ValueMember = "id";
                cboContractCustomer.SelectedIndex = 0;



            }
        }

        /// <summary>
        /// 查询条件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnContractGet_Click(object sender, EventArgs e)
        {
            GetContractData();
        }

        /// <summary>
        ///重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnContractReset_Click(object sender, EventArgs e)
        {
            txtContractName.Text = "";
            dtpContractTime.text = "";
            cboContractCustomer.SelectedIndex = 0;
        }

        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btncontractNext_Click(object sender, EventArgs e)
        {
            if (PageIndex < TotalSize)
            {
                PageIndex++;
                txtcontractPageIndex.Text = PageIndex.ToString();
                GetContractData();
            }
        }

        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btncontractLast_Click(object sender, EventArgs e)
        {
            if (PageIndex > 1)
            {
                PageIndex--;
                txtcontractPageIndex.Text = PageIndex.ToString();
                GetContractData();
            }
        }

        private async void btnContractDao_Click(object sender, EventArgs e)
        {
            var parameters = new Dictionary<string, string>
            {
                  { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },
                    { "Id", cboContractCustomer.SelectedValue == null ? string.Empty : cboContractCustomer.SelectedValue.ToString() },
                    { "Name", this.txtContractName.Text.Trim() },
                    { "CreateTime", this.dtpContractTime.Text },
            };

            // Assuming export endpoint is Sales/DiscountExport and returns ApiResponse<string> with file path or message
            byte[] excelBytes = await _apiClient.GetBytesAsync(
            endpoint: "Sales/ContractGetExport",
            parameters: parameters
             );

            using (var saveDialog = new SaveFileDialog())
            {
                saveDialog.Filter = "Excel文件 (*.xlsx)|*.xlsx|所有文件 (*.*)|*.*"; // 只允许保存xlsx格式
                saveDialog.Title = "保存销售合同导出文件";
                // 默认文件名：与后端一致（带时间戳，避免重复）
                saveDialog.FileName = $"销售合同_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                saveDialog.RestoreDirectory = true; // 打开时默认显示上次保存的路径

                // 若用户选择了保存路径
                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        // 将二进制流写入本地文件（完成保存）
                        System.IO.File.WriteAllBytes(saveDialog.FileName, excelBytes);

                        // 导出成功提示 + 可选打开文件
                        DialogResult openChoice = MessageBox.Show(
                            $"导出成功！\n文件已保存到：\n{saveDialog.FileName}\n是否立即打开文件？",
                            "导出成功",
                            MessageBoxButtons.YesNo,
                            MessageBoxIcon.Information
                        );

                        if (openChoice == DialogResult.Yes)
                        {
                            // 用系统默认程序（如WPS/Office）打开Excel
                            System.Diagnostics.Process.Start(saveDialog.FileName);
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        // 处理“无保存权限”错误（如选择C盘根目录）
                        MessageBox.Show("导出失败：没有文件保存权限！请选择桌面或其他有权限的路径。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    catch (System.IO.IOException ex)
                    {
                        // 处理“文件被占用”错误（如Excel已打开）
                        MessageBox.Show($"导出失败：文件被占用！\n原因：{ex.Message}\n请先关闭已打开的同名Excel文件。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        private void btnContractAdd_Click(object sender, EventArgs e)
        {
            ContracAddForm contracAddForm = new ContracAddForm(this);
            contracAddForm.Show();
        }

        #endregion

        #region 销售单

        /// <summary>
        /// 显示销售
        /// </summary>
        public async void GeTicketData()
        {
            var parameters = new Dictionary<string, string>
                {
                    { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },
                    { "Id", cboTicketCustomer.SelectedValue == null ? string.Empty : cboContractCustomer.SelectedValue.ToString() },
                    { "Number", this.txtTicketNumber.Text.Trim() },
                    { "SalesTime", this.txtTicketCreateTime.Text },
                };


            var response = await _apiClient.GetAsync<ApiResponse<List<Sales_TicketDTO>>>(
                    endpoint: "Sales/TicketGet",
                    parameters: parameters
                );
            if (response != null && response.code == 200)
            {
                dgvTicketGet.DataSource = response.pageData;
                TotalPages = response.totalCount;
                TotalSize = Convert.ToInt32(Math.Ceiling(TotalPages * 1.0 / PageSize));
                this.lblTicketPageSize.Text = TotalSize.ToString();
                dgvTicketGet.Columns["Id"].Visible = false;
                dgvTicketGet.Columns["Customer_Id"].Visible = false;
                //AddQuotationColumns();
            }
        }


        private void btnTicketNext_Click(object sender, EventArgs e)
        {
            if (PageIndex < TotalSize)
            {
                PageIndex++;
                lblTicketIndex.Text = PageIndex.ToString();
                GeTicketData();
            }
        }

        private void btnTicketlast_Click(object sender, EventArgs e)
        {
            if (PageIndex > 1)
            {
                PageIndex--;
                lblTicketIndex.Text = PageIndex.ToString();
                GeTicketData();
            }
        }

        private async void btnTicketDao_Click(object sender, EventArgs e)
        {
            var parameters = new Dictionary<string, string>
            {
                   { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },
                    { "Id", cboTicketCustomer.SelectedValue == null ? string.Empty : cboContractCustomer.SelectedValue.ToString() },
                    { "Number", this.txtTicketNumber.Text.Trim() },
                    { "SalesTime", this.txtTicketCreateTime.Text },
            };

            // Assuming export endpoint is Sales/DiscountExport and returns ApiResponse<string> with file path or message
            byte[] excelBytes = await _apiClient.GetBytesAsync(
            endpoint: "Sales/TicketGetExport",
            parameters: parameters
             );

            using (var saveDialog = new SaveFileDialog())
            {
                saveDialog.Filter = "Excel文件 (*.xlsx)|*.xlsx|所有文件 (*.*)|*.*"; // 只允许保存xlsx格式
                saveDialog.Title = "保存销售单导出文件";
                // 默认文件名：与后端一致（带时间戳，避免重复）
                saveDialog.FileName = $"销售单_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                saveDialog.RestoreDirectory = true; // 打开时默认显示上次保存的路径

                // 若用户选择了保存路径
                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        // 将二进制流写入本地文件（完成保存）
                        System.IO.File.WriteAllBytes(saveDialog.FileName, excelBytes);

                        // 导出成功提示 + 可选打开文件
                        DialogResult openChoice = MessageBox.Show(
                            $"导出成功！\n文件已保存到：\n{saveDialog.FileName}\n是否立即打开文件？",
                            "导出成功",
                            MessageBoxButtons.YesNo,
                            MessageBoxIcon.Information
                        );

                        if (openChoice == DialogResult.Yes)
                        {
                            // 用系统默认程序（如WPS/Office）打开Excel
                            System.Diagnostics.Process.Start(saveDialog.FileName);
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        // 处理“无保存权限”错误（如选择C盘根目录）
                        MessageBox.Show("导出失败：没有文件保存权限！请选择桌面或其他有权限的路径。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    catch (System.IO.IOException ex)
                    {
                        // 处理“文件被占用”错误（如Excel已打开）
                        MessageBox.Show($"导出失败：文件被占用！\n原因：{ex.Message}\n请先关闭已打开的同名Excel文件。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }


        private async void GetTicketSelect()
        {
            var response = await _apiClient.GetAsync<ApiResponse<List<Customer>>>(
                    endpoint: "Sales/CustomerGet"
                );
            if (response != null && response.code == 200)
            {
                var customerList = new List<Customer>
                {
                new Customer { id = 0, Customer_Name = "请选择"
                }
            };
                customerList.AddRange(response.data);
                cboTicketCustomer.DataSource = customerList;
                cboTicketCustomer.DisplayMember = "Customer_Name";//指定显示的字段
                cboTicketCustomer.ValueMember = "id";
                cboTicketCustomer.SelectedIndex = 0;



            }
        }


        private void btnTicketGet_Click(object sender, EventArgs e)
        {
            GeTicketData();
        }


        #endregion

        private void cbocustomer_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void lblcontractSize_Click(object sender, EventArgs e)
        {

        }

      
    }
}
